import axios from "axios"
import type { AxiosRequestConfig, Canceler } from "axios"
import { isFunction } from "@/utils/is"
import qs from "qs"

export const stringfyConfig = (config: AxiosRequestConfig) => {
	return [
		config.method,
		config.url,
		qs.stringify(config.data),
		qs.stringify(config.params),
	].join("&")
}

class Pending {
	pendingMap: Map<string, Canceler>
	constructor() {
		this.pendingMap = new Map<string, Canceler>()
	}
	add(config: AxiosRequestConfig) {
		const key = stringfyConfig(config)
		config.cancelToken =
			config.cancelToken ||
			new axios.CancelToken((cancel) => {
				this.pendingMap.set(key, cancel)
			})
	}
	remove(config: AxiosRequestConfig) {
		const key = stringfyConfig(config)
		if (this.pendingMap.has(key)) {
			config.cancelToken = undefined
			this.pendingMap.delete(key)
		}
	}
	removeAllPending() {
		this.pendingMap.forEach((cancel) => {
			cancel && isFunction(cancel) && cancel()
		})
		this.pendingMap.clear()
	}
}
const pendings = new Pending()
export default pendings
